package com.zhang.authoritycenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhang.authoritycenter.common.properties.ObsClientProperties;
import com.zhang.authoritycenter.common.util.AesUtil;
import com.zhang.authoritycenter.service.IThirdPartService;
import com.obs.services.ObsClient;
import com.obs.services.model.PostSignatureRequest;
import com.obs.services.model.PostSignatureResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2023-12-27 15:27
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ThirdPartServiceImpl implements IThirdPartService {

    private final ObsClient obsClient;
    private final ObsClientProperties obsClientProperties;

    /**
     * 加密key
     */
    private final String KEY_STR = "35e66ef603f1d503cbab4162";

    @Override
    public String getObsSign(String bucketName) {
        log.info("签名请求值：{}", bucketName);
        Map<String, String> map = getSign(bucketName);
        log.info("签名值：{}", map);
        return AesUtil.encrypt(JSON.toJSONString(map), KEY_STR);
    }

    /**
     * 获取签名
     */
    private Map<String, String> getSign(String bucketName) {
        log.info("请求obs签名，签名值,请求桶：{}", bucketName);
        if (StringUtils.isBlank(bucketName)) {
            bucketName = obsClientProperties.getBucketName();
        }
        PostSignatureRequest request = new PostSignatureRequest();
        // 设置表单参数
        Map<String, Object> formParams = new HashMap<>(3);
        // 设置对象访问权限为公共读
        formParams.put("x-obs-acl", "public-read");
        // 设置对象MIME类型
        formParams.put("content-type", "text/plain");
        request.setFormParams(formParams);
        // 设置表单上传请求有效期，单位：秒
        request.setExpires(3600);
        PostSignatureResponse response = obsClient.createPostSignature(request);
        log.info("OBS请求清明返回值:{}", response);
        // 获取表单上传请求参数
        Map<String, String> map = new HashMap<>(10);
        map.put("ak", obsClientProperties.getAccessKey());
        map.put("sk", obsClientProperties.getSecrtKey());
        map.put("endpoint", obsClientProperties.getEndpoint());
        map.put("bucketName", bucketName);
        map.put("policy", response.getPolicy());
        map.put("signature", response.getSignature());
        return map;
    }
}
